package indi.zhang.webbatch.mysql.batch;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import indi.zhang.webbatch.mysql.domain.OperationLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisCursorItemReader;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.configuration.support.JobRegistryBeanPostProcessor;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.transform.LineAggregator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;

import java.util.HashMap;
import java.util.Map;

@Configuration
@Slf4j
public class BatchSimple {
    @Autowired
    JobBuilderFactory jobBuilderFactory;
    @Autowired
    StepBuilderFactory stepBuilderFactory;
    @Autowired
    SqlSessionFactory sqlSessionFactory;

    /**
     * 如果没有该项配置，则手动启动时会报错No job configuration with the name [XJob] was registered
     * @param jobRegistry
     * @return
     */
    @Bean
    public JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor(JobRegistry jobRegistry){
        JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor = new JobRegistryBeanPostProcessor();
        jobRegistryBeanPostProcessor.setJobRegistry(jobRegistry);
        return jobRegistryBeanPostProcessor;
    }


    public static final String JOB = "job";
    private static final String STEP = "step";

    @Bean(name = JOB)
    Job job() {
        return jobBuilderFactory.get(JOB)
                .start(step())
                .build();
    }

    @Bean(name = STEP)
    Step step() {
        return stepBuilderFactory.get(STEP)
                .<OperationLog, OperationLog>chunk(5)
                .reader(itemReader())
                .writer(itemWriter())
                .build();
    }

    @Bean("itemReader")
    @StepScope
    MyBatisCursorItemReader<OperationLog> itemReader() {
        System.out.println("开始查询数据库");
        MyBatisCursorItemReader<OperationLog> reader = new MyBatisCursorItemReader<>();
        Map<String , Object> map = new HashMap<>();
//        map.put("id" , 2);
        reader.setQueryId("indi.zhang.webbatch.mysql.mapper.OperationLogMapper.selectAll");
        reader.setSqlSessionFactory(sqlSessionFactory);
        reader.setParameterValues(map);
        return reader;
    }

    @Bean("itemWriter")
    @StepScope
    FlatFileItemWriter<OperationLog> itemWriter() {
        System.out.println("开始写入文件中");
        FlatFileItemWriter<OperationLog> writer = new FlatFileItemWriter<>();
        writer.setResource(new FileSystemResource("F:\\music.txt"));//系统目录
        //将Music对象转换成字符串,并输出到文件
        writer.setLineAggregator(new LineAggregator<OperationLog>() {
            @Override
            public String aggregate(OperationLog music) {
                log.info(music.toString());
                ObjectMapper mapper = new ObjectMapper();
                String str = null;
                try {
                    str = mapper.writeValueAsString(music);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                return str;
            }
        });
        return writer;
    }
}
